package com.mlh.service.impl;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.mlh.enums.AppHttpCodeEnum;
import com.mlh.exception.SystemException;
import com.mlh.service.UploadService;
import com.mlh.util.ResponseResult;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @author 缪林辉
 * @date 2024/3/16 20:00
 * @DESCRIPTION
 */
@Service
@Data
//使用配置文件赋值 记得要给属性设置set()方法
@ConfigurationProperties(prefix = "oss")
public class UploadServiceImpl implements UploadService {
    private String accessKeyId;
    private String accessKeySecret;
    private String bucketName;
    private String endpoint;

    @Override
    public ResponseResult uploadImg(MultipartFile img) {
        //获取原始文件名 并 判断文件类型
        String originalFilename = img.getOriginalFilename();
        if(!originalFilename.endsWith("png")&&!originalFilename.endsWith("jpg")){//不是图片文件报错
            throw new SystemException(AppHttpCodeEnum.FILE_TYPE_ERROR);
        }
        //判断通过 直接上传至oss 不保存在服务器本地
        //为了防止图片名称重复问题，利用时间来区分
        //获取上传图片时间，作为命名的一部分,然后拼接上图片原始名称
        LocalDateTime currentTime = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM//dd/HHmmss");
        String filePath = currentTime.format(formatter);
        String url = uploadOss(img, filePath);
        return ResponseResult.okResult(url);
    }

    private String uploadOss(MultipartFile img, String filePath){
        String imgName=filePath+img.getOriginalFilename();
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint,accessKeyId,accessKeySecret);
        try {
            //将图片上传至OSS
            ossClient.putObject(bucketName, imgName,img.getInputStream());
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        //返回一个外网链接，但是阿里云不支持预览，只能强制下载
        String url="https://emyblogbucket-mlh.oss-cn-shenzhen.aliyuncs.com/"+imgName;
        return url;
    }
}
